<template>
    <view class="material-content">
        <view class="phone-model">
            <!-- <text class="title">机型：</text> -->
            <view class="phone-select">

                <hs-selectmachine style="display: inline-block;position:relative;" @selectModel="selectModel"><text
                        class="text1">▼</text></hs-selectmachine>
            </view>
        </view>
        <view class="material-name" @click="materialListShow = !materialListShow">
            <!-- <view class="material-name-content"> -->
            <image class="image" :src="baseImageUrl" mode="aspectFit"></image>
            <image class="image2" :src="frameImageUrl" mode="aspectFit"></image>
            <!-- </view> -->
            <text>{{ name }}</text>
            <text class="text1">▼</text>
        </view>

        <view v-if="showRight" class="material-right" @click="toggleDropdown">
            <!-- <text class="title">：</text> -->
            <text style="font-size: 28rpx;">{{ selectTransparent.name }}</text>
            <view class="arrow-icon" :class="{ 'arrow-open': show }">
                <text class="text1" style="font-size: 20rpx;color: #000;">▼</text>
            </view>
            <view v-if="show == true" class="dropdown-mask" @tag="closeMask" />
            <view class="dropdown-list-wrapper"
                :class="{ 'dropdown-list-show': show, 'dropdown-list-hide': !show && hasOpened }"
                @transitionend="onTransitionEnd">
                <view v-if="show || animating" class="dropdown-list">
                    <view class="dropdown-item" v-for="item in transparentList" :key="item.id"
                        @click="selectItem(item)">
                        {{ item.name }}
                    </view>
                </view>
            </view>
        </view>

        <view class="material-list"
            :style="arrayCount === 1 ? 'min-height: 300rpx;top: 100rpx;' : arrayCount === 2 ? 'min-height: 600rpx;top: 100rpx;' : arrayCount === 3 ? 'min-height: 900rpx;top: 100rpx;' : ''"
            v-if="materialListShow == true">
            <view class="" @click="materialListShow = false"
                style="height: 100vh;width: 100vw;position: absolute;top: 0;left: 0;">

            </view>
            <scroll-view scroll-x="true" class="material-scroll" enable-flex>
                <view class="material-item" v-for="(item, index) of normalMaterialList" :key="item.id"
                    :class="{ active: activeMaterialIndex == item.id }">
                    <radio checked class="radio" v-if="activeMaterialIndex == item.id" />
                    <view class="image" @click="selectMaterial(item, index)">
                        <image :src="item.baseImageUrl" mode="aspectFit"></image>
                        <image :src="item.frameImageUrl" mode="aspectFit"></image>
                    </view>
                    <view class="title">
                        {{ item.name }}
                    </view>
                </view>
            </scroll-view>
            <scroll-view scroll-x="true" class="material-scroll" enable-flex>
                <view class="material-item" v-for="(item) of type103MaterialList" :key="item.id"
                    :class="{ active: activeMaterialIndex == item.id }">
                    <radio checked class="radio" v-if="activeMaterialIndex == item.id" />
                    <view class="image" @click="selectMaterial(item, item.id)">
                        <image :src="item.baseImageUrl" mode="aspectFit"></image>
                        <image :src="item.frameImageUrl" mode="aspectFit"></image>
                    </view>
                    <view class="title">
                        {{ item.name }}
                    </view>
                </view>
            </scroll-view>
            <scroll-view scroll-x="true" class="material-scroll" enable-flex>
                <view class="material-item" v-for="(item) of type104MaterialList" :key="item.id"
                    :class="{ active: activeMaterialIndex == item.id }">
                    <radio checked class="radio" v-if="activeMaterialIndex == item.id" />
                    <view class="image" @click="selectMaterial(item, item.id)">
                        <image :src="item.baseImageUrl" mode="aspectFit"></image>
                        <image :src="item.frameImageUrl" mode="aspectFit"></image>
                    </view>
                    <view class="title">
                        {{ item.name }}
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>
<script>
import {
    getphoneModel,
    setDefaultPhoneModel
} from '@/api/user.js'
import {
    mapGetters,
    mapMutations
} from 'vuex'
export default {
    data() {
        return {
            model: {},
            list: [],
            multiArray: [
                [],
                []
            ],
            multiIndex: [0, 0],
            materialListShow: false,
            activeMaterialIndex: 0,
            name: '',
            baseImageUrl: '',
            frameImageUrl: '',
            show: false,
            animating: false,
            hasOpened: false,
            selectTransparent: { transparent: null, name: '全部图案', id: 0 },
            transparentList: [{ transparent: null, name: '全部图案', id: 0 }, { transparent: true, name: '透明图案', id: 1 }, { transparent: false, name: '不透明图案', id: 2 }],
        }
    },
    props: {
        materialType: { // 新增props标识页面类型
            type: String,
            default: '' // example/product/myCustom
        },
        materialList: {
            type: Array,
            default: []
        },
        showRight: {
            type: Boolean,
            default: false
        }
    },

    watch: {
        materialList: {
            immediate: true,
            deep: true, // 新增深度监听
            handler(newList) {
                if (!Array.isArray(newList) || newList.length === 0) {
                    console.log('materialList为空或未定义')
                    this.activeMaterialIndex = 0
                    this.name = '请选择材质'
                    this.baseImageUrl = ''  // 清空图片
                    this.frameImageUrl = ''
                    return
                }
                // 新增页面类型判断
                if (this.materialType === 'example' || this.materialType === 'product' || this.materialType === 'myCustom' || this.materialType === 'diyPhoneCase') {
                    // example页面交给父组件控制选择逻辑
                    return
                }
                const stored = this.getCurrentMaterial
                const defaultIndex = newList.findIndex(item =>
                    stored ?
                        item.materialMap[10] === stored.materialMap[10] :
                        item.defaulted
                )
                let activeIndex = defaultIndex === -1 ? 0 : defaultIndex; // 如果没有找到默认项，则默认为第一个
                const targetItem = newList[activeIndex];
                this.activeMaterialIndex = targetItem.id  // 存储实际id值
                this.name = targetItem.name
                this.baseImageUrl = targetItem.baseImageUrl
                this.frameImageUrl = targetItem.frameImageUrl
                // this.activeMaterialIndex = newList[activeIndex].id
                console.log('targetItem', targetItem)
                this.selectMaterial(targetItem, targetItem.id)
                // this.selectMaterial(newList[this.activeMaterialIndex], newList[this.activeMaterialIndex].id)
            }
        }
    },
    computed: {
        // ...mapGetters(['getCurrentMaterial']),
        getCurrentMaterial() {
            return this.$store.getters[`get${this.materialType}Material`]
        },
        normalMaterialList() {
            let normal = this.materialList.filter(i => i.materialSubType !== 103 && i.materialSubType !== 104);
            return normal;
        },
        type103MaterialList() {
            // let type103 = this.materialList.filter(i => i.materialSubType === 103);
            // if (type103.length === 0) return [];

            // for(let i = 0; i < type103.length; i++){
            //     type103[i].i = 7 + i;
            // }
            // console.log('type103',type103);
            // return type103;

            return this.materialList
                .filter(i => i.materialSubType === 103)
                .map((item, index) => ({
                    ...item,  // 创建新对象
                    i: 7 + index // 添加新属性
                }));
        },
        type104MaterialList() {
            return this.materialList
                .filter(i => i.materialSubType === 104)
                .map((item, index) => ({
                    ...item,  // 创建新对象
                    i: 7 + index // 添加新属性
                }));
        },
        // materialListStyle() {
        //     return this.materialListShow ? 'min-height: 600rpx;bottom: -635rpx;' : 'min-height: 300rpx;bottom: -350rpx;'
        // }
        arrayCount() {
            // 判断每个数组是否有长度（存在性）
            const hasArr1 = this.normalMaterialList?.length > 0; // 可选链避免undefined错误[[10,15]]
            const hasArr2 = this.type103MaterialList?.length > 0;
            const hasArr3 = this.type104MaterialList?.length > 0;

            // 统计存在数组的数量
            const count = [hasArr1, hasArr2, hasArr3].filter(Boolean).length;
            console.log('arrayCount', count)
            // 返回对应结果
            return count || 0; // 若都不存在则返回0（可根据需求调整）
        }
    },
    methods: {
        ...mapMutations(['setCurrentMaterial']),

        toggleDropdown() {
            if (!this.show) {
                this.animating = true;
                this.hasOpened = true;
            }
            this.show = !this.show;
        },
        onTransitionEnd() {
            if (!this.show) {
                this.animating = false;
            }
        },
        selectItem(item) {
            console.log('10', item);

            // this.show = false
            this.selectTransparent = item;
            this.$emit('handleSelectTransparent', item)
        },
        closeMask() {
            console.log('this.show', this.show);
            this.show = false
            console.log('this.show', this.show);
        },
        // 选择手机型号
        selectModel(data) {
            console.log(data)
            this._phoneModelId = data
            this.$emit('handleSelectModel', data)
            // uni.$u.debounce(() => {
            //     this.onRefresh()
            // })
        },
        getDefaultPhoneModel(currentMaterialIndex) {

            console.log('currentMaterial123', this.getCurrentMaterial);
            console.log('currentMaterialIndex456', currentMaterialIndex);
            if (this.getCurrentMaterial) {
                this.selectMaterial(this.getCurrentMaterial, currentMaterialIndex)
                return
            }

            console.log('getDefaultPhoneModel', this.materialList)
            if (this.materialList.length === 0) return;
            let activeMaterialIndex = this.materialList.findIndex((item, index) => {
                return item.defaulted
            })
            this.selectMaterial(this.materialList[activeMaterialIndex], this.materialList[activeMaterialIndex].id)
            console.log('activeMaterialIndex', this.activeMaterialIndex)
        },
        selectMaterial(item, index) {
            // this.$emit('handleSelectMaterial', item, index)
            console.log('selectMaterial', item, index)
            this.$emit('handleSelectMaterial', item, item.id)
        },
    },
    mounted() {

    }
}
</script>
<style lang="scss">
.material-content {
    display: flex;
    // padding: 10rpx;
    background-color: #fff;
    position: relative;
    justify-content: space-evenly;

    .phone-model {
        height: 50rpx;
        line-height: 50rpx;
        font-size: 28rpx;
        margin: 26rpx 0 0;
        position: relative;
        color: #979797;
        flex-shrink: 0;

        .phone-select {
            display: inline-block;
            border-radius: 50rpx;
            // border: 2rpx solid #333;
            padding: 0 17rpx;
            font-size: 28rpx;
            height: 50rpx;

            text {
                // font-weight: bold;
                color: #000 !important;
            }

            .text1 {
                margin-left: 17rpx;
                font-size: 20rpx;
            }
        }
    }

    .material-name {
        height: 100rpx;
        display: flex;

        // flex-grow: 1;
        .material-name-content {
            position: relative;

        }

        image {
            height: 100%;
            width: 70rpx;
            position: absolute;
        }

        text {
            font-size: 28rpx;
            margin: auto;
            margin-left: 72rpx;
        }

        .text1 {
            margin-left: 17rpx;
            font-size: 20rpx;
        }
    }

    .material-right {
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .dropdown-mask {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.2);
            z-index: 15;
        }

        .dropdown-list-wrapper {
            position: absolute;
            top: 100%;
            right: 0;
            transform: translateX(10%);
            width: auto;
            overflow: hidden;
            z-index: 16;
            transition: all 0.3s ease;
            transform-origin: top;
            opacity: 0;
            max-height: 0;
            transform: scaleY(0.9);
        }

        .dropdown-list-show {
            opacity: 1;
            max-height: 500px;
            transform: scaleY(1);
        }

        .dropdown-list-hide {
            opacity: 0;
            max-height: 0;
            transform: scaleY(0.9);
        }

        .dropdown-list {
            background-color: #fff;
            border-radius: 8px;
            // box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);

            .dropdown-item {
                padding: 30rpx;
                color: #000;
                font-size: 14px;
                border-bottom: 1px solid #2e3a59;
            }
        }

    }

    .material-list {
        // height: 600rpx;  // 增加弹出层高度
        // bottom: -600rpx;  // 增加弹出层高度

        //height: 300rpx;
        width: 100%;
        background-color: #fff;
        position: absolute;
        // bottom: -300rpx;
        left: 0;
        z-index: 999;
        box-shadow: -1rpx 10rpx 17rpx -7rpx #666;

        .material-scroll {
            display: flex;

            .material-item {
                height: 280rpx;
                width: 25vw;
                background-color: #fff;
                border-radius: 17rpx;
                //overflow: hidden;
                display: flex;
                flex-direction: column;
                position: relative;
                margin-right: 30rpx;
                text-align: center;
                flex-shrink: 0;

                &.active {
                    opacity: 0.7;

                    .radio {
                        position: absolute;
                        right: 17rpx;
                        top: 17rpx;
                        z-index: 1;
                    }
                }

                .image {
                    width: 100%;
                    height: 280rpx;
                    background: #fff;
                    position: relative;

                    image {
                        width: 100%;
                        height: 100%;
                        position: absolute;
                        top: 0;
                        left: 0;
                    }
                }

                .title {
                    font-size: 24rpx;
                    // margin: 17rpx;
                    flex-shrink: 0;
                    flex-grow: 0;
                    height: 50rpx;
                    // line-height: 50rpx;
                    line-height: 40rpx;
                }

                .item-btn {
                    height: 65.8rpx;
                    border-radius: 17rpx;
                    font-size: 30rpx;
                    box-sizing: border-box;
                    text-align: center;
                    line-height: 62.8rpx;
                    background-color: #333;
                    color: #fff;
                    margin: 17rpx;
                }
            }
        }

    }
}
</style>